<?php


namespace app\common\model\mysql;


use app\common\exception\MessageException;
use think\model\concern\SoftDelete;

class DriverFolder extends BaseModel
{
    use SoftDelete;

    protected $deleteTime = 'delete_time';

    // 设置当前模型对应的完整数据表名称
    protected $table = 'drive_folder';

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 模型初始化
    protected static function init()
    {
        // TODO:初始化内容
    }

    // 追加字段 type
    public function getIsFolderAttr($value){
        return true;
    }


    // 检查分类名是否存在
    public function checkName($name, $id = null)
    {
        if (!$name) {
            throw new MessageException(['msg' => '文件夹名不合法']);
        }

        // 设置查询条件
        $data = $this->where('name', $name);
        if ($id) {
            $data = $data->where('id', '<>', $id);
        }

        return $data->find();
    }

    public static function list(array $param = [])
    {
        $order = [
            'update_time' => 'desc',
            'create_time' => 'desc',
            'id' => 'desc'
        ];
        $where = [];
        // 筛选
        if (isset($param['name'])) {
            $where[] = ['name', 'like', '%' . $param['name'] . '%'];
        }
        // 0 会为true
        if (isset($param['folder_id']) && $param['folder_id'] != '') {
            $where[] = ['parent_id', '=', $param['folder_id']];
        }

        $list = self::where($where)->order($order)->select()->append(['is_folder']);
        return $list;
    }

    public function getTreeList(array $param = [])
    {
        $list = $this->where('status', '>', '0')->select();
        $list = $list->hidden(['sort', 'status', 'update_time', 'create_time'])->toArray();
        return $this->getTreeData($list);
    }

    /**
     * 获取树状列表
     * @param $list
     * @param int $parentId
     * @return array
     */
    private function getTreeData($list, int $parentId = 0, $level = 0)
    {
        $data = [];
        foreach ($list as $key => $item) {
            if ($item['parent_id'] == $parentId) {
                // 路径 path 处理
                $item['level'] = $level;
                $children = $this->getTreeData($list, $item['id'], $level + 1);
                !empty($children) && $item['children'] = $children;

                $data[] = $item;
                unset($list[$key]);
            }
        }
        return $data;
    }
}